package com.yanqu.road.server.manager.activity.suitang.manager;

import com.yanqu.road.entity.activity.suitang.data.*;
import com.yanqu.road.entity.activity.suitang.entity.battle.CrossSuiTangBattleResult;
import com.yanqu.road.entity.activity.suitang.entity.battle.CrossSuiTangBattlefieldRank;
import com.yanqu.road.entity.activity.suitang.entity.team.CrossSuiTangTeam;
import com.yanqu.road.entity.activity.suitang.entity.union.CrossSuiTangUnionJoinMember;
import com.yanqu.road.entity.activity.suitang.entity.user.CrossSuiTangUserRound;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangWarType;
import com.yanqu.road.entity.activity.suitang.enums.eSuiTangStage;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eSceneType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.scene.UserScene;
import com.yanqu.road.entity.scene.UserSceneGroup;
import com.yanqu.road.pb.activity.suitang.SuiTang;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.npc.CrossNpcUserMgr;
import com.yanqu.road.server.manager.scene.CrossSceneMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mina.util.ConcurrentHashSet;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class CrossSuiTangSyncActivityMgr extends CrossBaseActivityMgr {

    protected static Logger logger = LogManager.getLogger(CrossSuiTangSyncActivityMgr.class.getName());

    // 需要同步的战斗结果，同步完就清空
    private Map<String, Set<CrossSuiTangBattleResult>> needSyncBattleResultMap = new ConcurrentHashMap<>();
    private Map<String, CrossSuiTangCity> needSyncCityMap = new ConcurrentHashMap<>();

    // 需要同步的内容
    private final Map<String, Set<Integer>> needSyncTeam = new ConcurrentHashMap<>();

    /*
     * 同步队伍数据
     */
    public void syncTeamToSelf(CrossSuiTangTeam team) {
        SuiTang.SuiTangSyncTeamRespMsg.Builder builder = SuiTang.SuiTangSyncTeamRespMsg.newBuilder();
        builder.addTeam(activity.parseSuiTangTeamMsg(team));
        CrossSuiTangUserRound curUserRound = getCurUserRound(team.getUserId());
        if (curUserRound == null) {
            return;
        }
        UserScene userScene = CrossSceneMgr.getUserScene(team.getUserId());
        if (userScene == null) {
            return;
        }

        List<Integer> list = activity.sceneKeyToList(userScene.getSceneId());
        if (list != null && !list.isEmpty() && list.size() >= 4 && list.get(2) == curUserRound.getWarType().getType() && list.get(3) == curUserRound.getActGroupId()) {
            activity.sendPacket(ClientProtocol.U_SUI_TANG_SYNC_TEAM, builder, team.getUserId());
        }
    }

    /*
     * 同步跑马灯
     */
    public void syncTopMsg(boolean isDefWin, boolean isOut, String ackUnionId, String defUnionId, CrossSuiTangCity city) {
        SuiTang.SuiTangSyncTopMsgRespMsg.Builder builder = SuiTang.SuiTangSyncTopMsgRespMsg.newBuilder();
        builder.setCityId(city.getCityId());
        builder.setUnionId(ackUnionId);
        builder.setType(isDefWin ? 2 : 1);
        builder.setDefUnionId(defUnionId);
        builder.setOutUnionId(isOut ? defUnionId : "");
        long now = System.currentTimeMillis();
        List<Long> recUsers = activity.getUserDataMap().values().stream().filter(item -> activity.isInActivity(item, now)
                && activity.isInActivityGroup(item, city.getWarType(), city.getActGroupId())
        ).map(CrossSuiTangUserData::getUserId).collect(Collectors.toList());
        if (recUsers.isEmpty()) {
            return;
        }
        activity.sendPacketToAll(ClientProtocol.U_SUI_TANG_SYNC_TOP_MSG, builder, recUsers);
    }

    /*
     * 同步城池数据
     */
    public void syncCity(CrossSuiTangCity city, boolean isNowSync) {
        synchronized (needSyncCityMap) {
            needSyncCityMap.put(activity.getSceneKey(city.getCityId(), city.getWarType(), city.getActGroupId()), city);
            if (needSyncCityMap.size() > 20 || isNowSync) {
                syncCityToAll();
            }
        }
    }

    public void syncCityToAll() {
        Map<eSuiTangWarType, Map<Integer, List<CrossSuiTangCity>>> warTypeMap = new ConcurrentHashMap<>();
        warTypeMap.put(eSuiTangWarType.WAR_TYPE_YIJUN, new ConcurrentHashMap<>());
        warTypeMap.put(eSuiTangWarType.WAR_TYPE_XIAOQI, new ConcurrentHashMap<>());
        warTypeMap.put(eSuiTangWarType.WAR_TYPE_JINJUN, new ConcurrentHashMap<>());
        Map<String, CrossSuiTangCity> tempSyncCity = null;
        synchronized (needSyncCityMap) {
            if (needSyncCityMap.size() == 0) {
                return;
            }
            tempSyncCity = new ConcurrentHashMap<>(needSyncCityMap);
            needSyncCityMap.clear();
        }
        if (tempSyncCity == null) {
            return;
        }
        long now = System.currentTimeMillis();
        for (CrossSuiTangCity city : tempSyncCity.values()) {
            List<CrossSuiTangCity> cityList = warTypeMap.get(city.getWarType()).computeIfAbsent(city.getActGroupId(), k -> new ArrayList<>());
            cityList.add(city);
        }
        List<Long> recUsers = new ArrayList<>();
        for (Map<Integer, List<CrossSuiTangCity>> actGroupMap : warTypeMap.values()) {
            for (List<CrossSuiTangCity> cityList : actGroupMap.values()) {
                if (cityList == null || cityList.isEmpty()) {
                    continue;
                }
                recUsers = activity.getUserDataMap().values().stream().filter(item -> activity.isInActivity(item, now) && activity.isInActivityGroup(item, cityList.get(0).getWarType(), cityList.get(0).getActGroupId())).map(CrossSuiTangUserData::getUserId).collect(Collectors.toList());
                if (recUsers.isEmpty()) {
                    continue;
                }
                SuiTang.SuiTangSyncCityRespMsg.Builder builder = SuiTang.SuiTangSyncCityRespMsg.newBuilder();
                for (CrossSuiTangCity city : cityList) {
                    builder.addCity(activity.parseSuiTangCityMsg(city));
                }
                activity.sendPacketToAll(ClientProtocol.U_SUI_TANG_SYNC_CITY, builder, recUsers);
            }
        }
        warTypeMap.clear();
    }

    /*
     * 同步城池事件
     */
    public void syncCityEvent() {
        long now = System.currentTimeMillis();
        eSuiTangWarType warType = eSuiTangWarType.WAR_TYPE_YIJUN;
        int actGroupId = -1;
        SuiTang.SyncSuiTangCityEventRespMsg.Builder builder = SuiTang.SyncSuiTangCityEventRespMsg.newBuilder();
        Map<Integer, eSuiTangWarType> warTypeMapTemp = new ConcurrentHashMap<>();
        warTypeMapTemp.put(eSuiTangWarType.WAR_TYPE_YIJUN.getType(), eSuiTangWarType.WAR_TYPE_YIJUN);
        warTypeMapTemp.put(eSuiTangWarType.WAR_TYPE_XIAOQI.getType(), eSuiTangWarType.WAR_TYPE_XIAOQI);
        warTypeMapTemp.put(eSuiTangWarType.WAR_TYPE_JINJUN.getType(), eSuiTangWarType.WAR_TYPE_JINJUN);
        for (int i = eSuiTangWarType.WAR_TYPE_YIJUN.getType(); i <= eSuiTangWarType.WAR_TYPE_JINJUN.getType(); i++) {
            Map<Integer, Map<Integer, CrossSuiTangCityEvent>> cityEventGroupMap = getCityEventGroupMap(warTypeMapTemp.get(i));
            for (Map<Integer, CrossSuiTangCityEvent> eventMap : cityEventGroupMap.values()) {
                for (CrossSuiTangCityEvent event : eventMap.values()) {
                    warType = event.getWarType();
                    actGroupId = event.getActGroupId();
                    builder.addEvent(activity.parseSuiTangCityEventMsg(event));
                }
                if (actGroupId == -1) {
                    builder.clear();
                    continue;
                }
                eSuiTangWarType finalWarType = warType;
                int finalActGroupId = actGroupId;
                List<Long> recUsers = activity.getUserDataMap().values().stream().filter(item -> activity.isInActivity(item, now) && activity.isInActivityGroup(item, finalWarType, finalActGroupId)).map(CrossSuiTangUserData::getUserId).collect(Collectors.toList());
                if (recUsers.isEmpty()) {
                    builder.clear();
                    continue;
                }
                activity.sendPacketToAll(ClientProtocol.U_SUI_TANG_SYNC_CITY_EVENT, builder, recUsers);
                builder.clear();
            }
        }
    }

    /*
     * 同步自动行军错误
     */
    public void syncAutoMoveFail(long userId, int ret, boolean isChangeSoldier) {
        if (ret == 0) {
            return;
        }
        if (activity.getNpcTestActivityMgr().isNpc(userId)) {
            return;
        }

        if (isChangeSoldier) {
            // 补兵失败，要回复一下消息
            SuiTang.SuiTangChangeTeamSoldierRespMsg.Builder respMsg = SuiTang.SuiTangChangeTeamSoldierRespMsg.newBuilder();
            respMsg.setRet(ret);
            activity.sendPacket(ClientProtocol.U_SUI_TANG_CHANGE_TEAM_SOLDIER, respMsg, userId);
        } else {
            // 移动失败，要回复一下消息
            SuiTang.SuiTangMoveTeamRespMsg.Builder builder = SuiTang.SuiTangMoveTeamRespMsg.newBuilder();
            builder.setRet(ret);
            activity.sendPacket(ClientProtocol.U_SUI_TANG_MOVE_TEAM, builder, userId);
        }
    }

    /*
     * 同步兵营
     */
    public void syncBarracks(long userId) {
        if (activity.getNpcTestActivityMgr().isNpc(userId)) {
            return;
        }
        SuiTang.SuiTangSyncBarracksRespMsg.Builder syncMsg = SuiTang.SuiTangSyncBarracksRespMsg.newBuilder();
        syncMsg.setBarracks(activity.parseSuiTangBarracksMsg(userId));
        activity.sendPacket(Protocol.U_SUI_TANG_SYNC_BARRACKS, syncMsg, userId);
    }

    /*
     * 同步战斗结果
     */
    public void syncBattleResultMsg(CrossSuiTangCity city) {
        if (activity == null) {
            return;
        }

        if (city == null) {
            for (Map.Entry<String, CrossSuiTangCity> entry : needSyncCityMap.entrySet()) {
                city = entry.getValue();
                List<Long> battlefieldUserIdList = activity.getSceneUserIdList(eSceneType.SuiTangBattlefield, city.getCityId(), city.getWarType(), city.getActGroupId());
                if (battlefieldUserIdList == null || battlefieldUserIdList.isEmpty()) {
                    continue;
                }
                SuiTang.SuiTangBattlefieldMsg.Builder builder = activity.parseSuiTangBattlefieldMsgForSync(city.getBattlefield(), city);
                activity.sendPacketToAll(ClientProtocol.U_SUI_TANG_CITY_BATTLE, builder, battlefieldUserIdList);
            }
            needSyncBattleResultMap.clear();
        } else {
            List<Long> battlefieldUserIdList = activity.getSceneUserIdList(eSceneType.SuiTangBattlefield, city.getCityId(), city.getWarType(), city.getActGroupId());
            if (battlefieldUserIdList == null || battlefieldUserIdList.isEmpty()) {
                return;
            }
            SuiTang.SuiTangSyncCityBattleMsg.Builder builderSync = SuiTang.SuiTangSyncCityBattleMsg.newBuilder();
            SuiTang.SuiTangBattlefieldMsg.Builder builder = activity.parseSuiTangBattlefieldMsgForSync(city.getBattlefield(), city);
            String scene = activity.getSceneKey(city.getCityId(), city.getWarType(), city.getActGroupId());
            builderSync.setBattlefield(builder);
            activity.sendPacketToAll(ClientProtocol.U_SUI_TANG_CITY_BATTLE, builderSync, battlefieldUserIdList);
            needSyncBattleResultMap.remove(scene);
        }
    }

    /*
     * 同步城池战报给同组内商会
     */
    public void syncCityWarReportToActGroup(CrossSuiTangCityWarReportData report, CrossSuiTangCity city) {
        SuiTang.SuiTangCityWarReportRespMsg.Builder respMsg = SuiTang.SuiTangCityWarReportRespMsg.newBuilder();
        respMsg.setRet(0);
        SuiTang.SuiTangCityWarReportMsg.Builder tempMsg = SuiTang.SuiTangCityWarReportMsg.newBuilder();
        for (String atkCampId : report.getAtkCampId()) {
            tempMsg.addAtkUnionId(atkCampId);
        }
        tempMsg.setDefUnionId(report.getDefCampId());
        tempMsg.setType(report.getType());
        tempMsg.setCityId(report.getCityId());
        tempMsg.setTime(report.getTime());
        for (CrossSuiTangBattlefieldRank atkRank : report.getAtkRankList()) {
            tempMsg.addAtkRank(activity.parseSuiTangBattlefieldRankMsg(atkRank));
        }
        for (CrossSuiTangBattlefieldRank defRank : report.getDefRankList()) {
            tempMsg.addDefRank(activity.parseSuiTangBattlefieldRankMsg(defRank));
        }
        tempMsg.setWinUnionId(report.getWinCampId());
        respMsg.addList(tempMsg);
        long now = System.currentTimeMillis();
        List<Long> recUsers = activity.getUserDataMap().values().stream().filter(item -> activity.isInActivity(item, now) && activity.isInActivityGroup(item, city.getWarType(), city.getActGroupId())).map(CrossSuiTangUserData::getUserId).collect(Collectors.toList());
        if (recUsers.isEmpty()) {
            return;
        }
        activity.sendPacketToAll(ClientProtocol.U_SUI_TANG_CITY_WAR_REPORT, respMsg, recUsers);
    }

    /*
     * 同步城池战报
     */
    public void syncCityWarReport(CrossSuiTangCityWarReportData report, long userId) {
        SuiTang.SuiTangCityWarReportRespMsg.Builder respMsg = SuiTang.SuiTangCityWarReportRespMsg.newBuilder();
        respMsg.setRet(0);
        CrossSuiTangUserData userData = activity.getUserData(userId);
        if (Objects.equals(report.getDefCampId(), userData.getUnionUid()) || report.getAtkCampId().contains(userData.getUnionUid())) {
            SuiTang.SuiTangCityWarReportMsg.Builder tempMsg = SuiTang.SuiTangCityWarReportMsg.newBuilder();
            for (String atkCampId : report.getAtkCampId()) {
                tempMsg.addAtkUnionId(atkCampId);
            }
            tempMsg.setDefUnionId(report.getDefCampId());
            tempMsg.setType(report.getType());
            tempMsg.setCityId(report.getCityId());
            tempMsg.setTime(report.getTime());
            for (CrossSuiTangBattlefieldRank atkRank : report.getAtkRankList()) {
                tempMsg.addAtkRank(activity.parseSuiTangBattlefieldRankMsg(atkRank));
            }
            for (CrossSuiTangBattlefieldRank defRank : report.getDefRankList()) {
                tempMsg.addDefRank(activity.parseSuiTangBattlefieldRankMsg(defRank));
            }
            tempMsg.setWinUnionId(report.getWinCampId());
            respMsg.addList(tempMsg);
            activity.sendPacket(ClientProtocol.U_SUI_TANG_CITY_WAR_REPORT, respMsg, userId);
        }
    }

    /*
     * 同步所有玩家基础分组数据
     */
    public void syncBaseDataMsgToAll() {
        for (CrossSuiTangUserData user : activity.getUserDataMap().values()) {
            syncBaseDataMsg(user.getUserId());
            syncUserDataToGameServer(user);
        }
        for (CrossSuiTangUnionJoinData unionJoinData : activity.getUnionJoinDataMap().values()) {
            syncCommanderInfoToUnion(unionJoinData.getUnionUid());
        }
    }

    /*
     * 同步基础数据
     */
    public void syncBaseDataMsg(long userId) {
        if (activity == null) {
            return;
        }
        if (activity.getNpcTestActivityMgr().isNpc(userId)) {
            return;
        }
        int joinStatus = 0; // 参与活动状态：0无资格、1有资格、2分组还没出
        if (activity.getCrossSuiTangData().getLockUnion()) {
            joinStatus = activity.isAble(userId) ? 1 : 0;
        } else {
            for (CrossSuiTangUnionJoinData join : activity.getUnionJoinDataMap().values()) {
                if (join.getMemberMap().containsKey(userId)) {
                    joinStatus = 2;
                    break;
                }
            }
        }

        SuiTang.SuiTangSyncBaseDataRespMsg.Builder builder = SuiTang.SuiTangSyncBaseDataRespMsg.newBuilder();
        builder.setJoinStatus(joinStatus);
        builder.setSyncPatronsTime(0);
        if (activity.isAble(userId)) {
            if (activity.getCrossSuiTangData().getLockUnion()
                    && getCurUserRound(userId) != null) {
                builder.setRound(activity.parseSuiTangUserRoundSyncMsg(getCurUserRound(userId)));
            }

            CrossSuiTangUserData userData = activity.getUserData(userId);
            builder.setSyncPatronsTime(userData.getLastSyncPatronsTime());
            if (userData.getUserBaseInfo().getTitleId() > 0) {
                builder.setTitleId(userData.getUserBaseInfo().getTitleId());
                builder.setHonoraryTitle(userData.getUserBaseInfo().getHonoraryTitle());
            }
        }
        activity.sendPacket(ClientProtocol.U_SUI_TANG_SYNC_BASE_DATA, builder, userId);
    }

    /**
     * 跨服同步用户数据到游戏服
     */
    public void syncUserDataToGameServer(CrossSuiTangUserData userData) {
        if (userData == null || activity.getNpcTestActivityMgr().getNpcIdList().contains(userData.getUserId())) {
            return;
        }
        SuiTang.CrossSuiTangSyncUserDataMsg.Builder builder = SuiTang.CrossSuiTangSyncUserDataMsg.newBuilder();
        builder.setUnionId(userData.getUnionUid());
        builder.setZhanGong(userData.getZhanGong());
        builder.setPositionId(userData.getPositionId());
        builder.setSpeedUpNum(userData.getTeam() != null ? userData.getTeam().getSpeedUpNum() : 0);
        activity.sendPacket(GameProtocol.S_CROSS_SUI_TANG_SYNC_USER_DATA, builder, userData.getUserId());
    }

    public void syncWaitReward(CrossSuiTangUserData userData) {
        if (userData == null || activity.getNpcTestActivityMgr().getNpcIdList().contains(userData.getUserId())) {
            return;
        }
        String sendReward = PropertyHelper.parsePropertyToString(userData.getWaitReward());
        if (StringUtils.isNullOrEmpty(sendReward)) {
            return;
        }
        // 清空奖励
        userData.setWaitReward(new Property());
        SuiTang.CrossSuiTangWaitRewardMsg.Builder builder = SuiTang.CrossSuiTangWaitRewardMsg.newBuilder();
        builder.setWaitReward(sendReward);
        activity.sendPacket(GameProtocol.S_CROSS_SUI_TANG_SYNC_WAIT_REWARD, builder, userData.getUserId());
    }

    /**
     * 通知游戏服condition更新值
     */
    public void notifyConditionChange(long userId, eGamePlayerEventType type, long value, String paramStr) {
        if (activity.getNpcTestActivityMgr().isNpc(userId)) {
            return;
        }
        SuiTang.CrossSuiTangNotifyConditionRespMsg.Builder builder = SuiTang.CrossSuiTangNotifyConditionRespMsg.newBuilder();
        builder.setActivityId(activity.getConfig().getActivityId());
        builder.setUserId(userId);
        builder.setConditionType(type.getValue());
        builder.setValue(value);
        builder.setParam(paramStr);
        activity.sendPacket(GameProtocol.S_SUI_TANG_NOTIFY_CONDITION_FROM_CROSS, builder, userId);
    }

    /**
     * 通知游戏服condition更新值(商会所有人)
     */
    public void notifyConditionChangeToUnion(String unionId, eGamePlayerEventType type, long value, String paramStr) {
        CrossSuiTangUnionJoinData unionJoin = getUnionJoin(unionId);
        if (unionJoin == null) {
            return;
        }
        for (CrossSuiTangUnionJoinMember member : unionJoin.getMemberMap().values()) {
            if (activity.getNpcTestActivityMgr().isNpc(member.getUserId())) {
                continue;
            }
            notifyConditionChange(member.getUserId(), type, value, paramStr);
        }
    }

    /*
     * 同步宝箱值去本服改condition
     */
    public void syncRedPacketBoxValue(String unionId) {
        if (!ActivityMgr.activityInShowTime(activity.getConfig().getActivityInfo())) {
            return;
        }
        if (!unionId.isEmpty()) {
            CrossSuiTangUnionData unionData = getUnionData(unionId);
            if (unionData != null && unionData.getRedPacketValue() > 0 && !unionData.getUnionUid().isEmpty()) {
                Map<Long, List<Long>> serverUserMap = getCampServerIdUserIdMap(unionData.getUnionUid());
                for (long serverId : serverUserMap.keySet()) {
                    SuiTang.CrossSuiTangRedPacketBoxValueSyncMsg.Builder syncMsg = SuiTang.CrossSuiTangRedPacketBoxValueSyncMsg.newBuilder();
                    syncMsg.setActivityId(unionData.getActivityId());
                    for (long userId : serverUserMap.get(serverId)) {
                        if (activity.getNpcTestActivityMgr().isNpc(userId)) {
                            continue;
                        }
                        syncMsg.addUserIds(userId);
                    }
                    syncMsg.setValue(unionData.getRedPacketValue());
                    MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_CROSS_SUI_TANG_RED_PACKET_BOX_VALUE_SYNC, syncMsg));
                }
            }
            return;
        }
        for (CrossSuiTangUnionData unionData : new ConcurrentHashMap<>(activity.getUnionDataMap()).values()) {
            if (unionData.getRedPacketValue() > 0 && !unionData.getUnionUid().isEmpty()) {
                Map<Long, List<Long>> serverUserMap = getCampServerIdUserIdMap(unionData.getUnionUid());
                for (long serverId : serverUserMap.keySet()) {
                    SuiTang.CrossSuiTangRedPacketBoxValueSyncMsg.Builder syncMsg = SuiTang.CrossSuiTangRedPacketBoxValueSyncMsg.newBuilder();
                    syncMsg.setActivityId(unionData.getActivityId());
                    for (long userId : serverUserMap.get(serverId)) {
                        if (activity.getNpcTestActivityMgr().isNpc(userId)) {
                            continue;
                        }
                        syncMsg.addUserIds(userId);
                    }
                    syncMsg.setValue(unionData.getRedPacketValue());
                    MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_CROSS_SUI_TANG_RED_PACKET_BOX_VALUE_SYNC, syncMsg));
                }
            }
        }
    }

    private Map<Long, List<Long>> getCampServerIdUserIdMap(String unionId) {
        Map<Long, List<Long>> resMap = new ConcurrentHashMap<>();
        CrossSuiTangUnionJoinData unionJoinData = activity.getUnionJoinDataMap().get(unionId);
        if (unionJoinData != null) {
            for (CrossSuiTangUnionJoinMember value : unionJoinData.getMemberMap().values()) {
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(value.getUserId());
                if (userBaseInfo != null) {
                    if (!resMap.containsKey(userBaseInfo.getServerId())) {
                        resMap.put(userBaseInfo.getServerId(), new ArrayList<>());
                    }
                    resMap.get(userBaseInfo.getServerId()).add(value.getUserId());
                }
            }
        }
        return resMap;
    }

    /**
     * 同步指挥官信息
     */
    public void syncCommanderInfo(long userId, String unionId) {
        if (Objects.equals(unionId, "")) {
            return;
        }
        if (activity.getNpcTestActivityMgr().isNpc(userId)) {
            return;
        }
        SuiTang.SuiTangCommanderDataSyncMsg.Builder syncMsg = activity.parseSuiTangCommanderDataSyncMsg(activity.getUnionDataMap().get(unionId));
        activity.sendPacket(ClientProtocol.U_SUI_TANG_COMMANDER_DATA_SYNC, syncMsg, userId);
    }

    /*
     * 同步指挥官信息给商会所有人
     */
    public void syncCommanderInfoToUnion(String unionId) {
        if (unionId.isEmpty()) {
            return;
        }
        SuiTang.SuiTangCommanderDataSyncMsg.Builder syncMsg = activity.parseSuiTangCommanderDataSyncMsg(activity.getUnionDataMap().get(unionId));
        // 同步给阵营所有玩家
        List<Long> campUserList = activity.getUserDataMap().values().stream().filter(item -> item.getUnionUid().equals(unionId) && !activity.getNpcTestActivityMgr().isNpc(item.getUserId())).mapToLong(CrossSuiTangUserData::getUserId).boxed().collect(Collectors.toList());
        activity.sendPacketToAll(ClientProtocol.U_SUI_TANG_COMMANDER_DATA_SYNC, syncMsg, campUserList);
    }

    public void addNeedSyncBattleResult(CrossSuiTangBattleResult ret, String scene) {
        Set<CrossSuiTangBattleResult> resultSet = needSyncBattleResultMap.get(scene);
        if (resultSet == null) {
            resultSet = new ConcurrentHashSet<>();
            needSyncBattleResultMap.put(scene, resultSet);
        }
        resultSet.add(ret);
//        needSyncCityMap.put(scene, ret.getCity());
    }

    public void removeNeedSyncBattleResult(CrossSuiTangBattleResult ret, String scene) {
        Set<CrossSuiTangBattleResult> resultSet = needSyncBattleResultMap.get(scene);
        if (resultSet == null) {
            return;
        }
        resultSet.remove(ret);
    }

    public Map<String, Set<CrossSuiTangBattleResult>> getNeedSyncBattleResultMap() {
        return needSyncBattleResultMap;
    }
}
